package com.example.Holo.uiactivities;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.ActionBar;
import com.example.Holo.EmptyTabListenerSherlockActivity;
import com.example.Holo.R;
import com.google.common.base.Supplier;

import java.util.*;

import static android.content.Intent.ACTION_VIEW;
import static android.net.Uri.withAppendedPath;
import static android.provider.BaseColumns._ID;
import static android.provider.ContactsContract.Contacts.*;
import static com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_TABS;
import static com.google.common.base.Suppliers.memoize;
import static java.lang.String.valueOf;
import static java.util.Collections.sort;

public class MyActivity extends EmptyTabListenerSherlockActivity {

    private final static String[] PROJECTION = new String[]{_ID, DISPLAY_NAME, STARRED};
    private final static String FAVORITES = STARRED + "='1'";

    private ArrayAdapter adapter;
    private List<String> contacts = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);

        getSupportActionBar().setNavigationMode(NAVIGATION_MODE_TABS);
        final ActionBar.Tab allContacts = getSupportActionBar().newTab();
        allContacts.setText(R.string.all_contacts);
        allContacts.setTabListener(this);
        getSupportActionBar().addTab(allContacts);
        final ActionBar.Tab favoritesContacts = getSupportActionBar().newTab();
        favoritesContacts.setText(R.string.favorites);
        favoritesContacts.setTabListener(this);
        getSupportActionBar().addTab(favoritesContacts);

        final ListView contactsListView = (ListView) findViewById(R.id.contacts);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contacts);
        contactsListView.setAdapter(adapter);

        loader.loadAndShow(null);
    }

    private Map<String, String> getContacts(String condition) {
        final Map<String, String> contactMap = new HashMap<String, String>();
        final ContentResolver cr = getContentResolver();
        final Cursor cursor = cr.query(CONTENT_URI, PROJECTION, condition, null, null);
        while (cursor.moveToNext()) {
            final String contactID = cursor.getString(cursor.getColumnIndex(_ID));
            final Intent intent = new Intent(ACTION_VIEW);
            final Uri uri = withAppendedPath(CONTENT_URI, valueOf(contactID));
            intent.setData(uri);
            final String title = (cursor.getString(cursor.getColumnIndex(DISPLAY_NAME)));
            contactMap.put(title, intent.toUri(0));
        }
        cursor.close();
        return contactMap;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        contacts.clear();
        switch (tab.getPosition()) {
            case 0:
                loader.loadAndShow(null);
                break;
            case 1:
                loader.loadAndShow(FAVORITES);
                break;
        }
    }

    interface ILoader {
        void loadAndShow(String condition);
    }

    private final ILoader loader = new ILoader() {
        @Override
        public void loadAndShow(final String condition) {
            final Map<String, String> result = memoize(new Supplier<Map<String, String>>() {
                @Override
                public Map<String, String> get() {
                    return getContacts(condition);
                }
            }).get();
            contacts.clear();
            final List<String> collection = new ArrayList<String>(result.keySet());
            sort(collection, comparator);
            contacts.addAll(collection);
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }
    };

    private static final Comparator<String> comparator = new Comparator<String>() {
        @Override
        public int compare(String first, String second) {
            return first.compareTo(second);
        }
    };
}
